﻿using ORM;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ORM
{
    

    public class DbSuger : SqlSugarClient
    {

        
        //public DbSuger(ConfigModel databaseCofig) 
        //{
        //    DbConfigCommon dbconfig = new DbConfigCommon();
        //     new DbSuger(dbconfig.GetSqlSugarConfig(databaseCofig));
        //}

        public DbSuger(ConnectionConfig config) : base(config)
        {
           // SqlSugarEvent();
        }

        public DbSuger(List<ConnectionConfig> configs) : base(configs)
        {
           // SqlSugarEvent();
        }

        public void SqlSugarEvent()
        {
            //设置超时时间
            Ado.CommandTimeOut = 30000;
            //可以修改SQL和参数的值
            Aop.OnExecutingChangeSql = (sql, pars) => 
            {
                return new KeyValuePair<string, SugarParameter[]>(sql, pars);
            };
            //SQL执行前事件
            Aop.OnLogExecuting = (sql, pars) =>
            {

            };
            //SQL执行完事件
            Aop.OnLogExecuted = (sql, pars) =>
            {
                //sql执行时间
                var time = Ado.SqlExecutionTime.TotalMilliseconds;
                //获取参数值
                var Params = GetParams(pars);
            };
            //执行SQL 错误事件
            Aop.OnError = (exp) =>
            {
                //出错信息
                var msg = exp.Message;
                //出错的sql
                var sql = exp.Sql;
                throw new Exception(msg + "," + sql);
            };
            //可以方便拿到 数据库操作前和操作后的数据变化。
            Aop.OnDiffLogEvent = (it) =>
            {
                //变化前数据
                var editBeforeData = it.BeforeData;
                //变化后数据
                var editAfterData = it.AfterData;
                //SQL
                var sql = it.Sql;
                //参数
                var parameter = it.Parameters;
                //业务数据
                var data = it.BusinessData;
                //时间
                var time = it.Time ?? new TimeSpan();
                //枚举值 insert 、update 和 delete 用来作业务区分
                var diffType = it.DiffType;
            };
        }

        /// <summary>
        /// 获取参数信息
        /// </summary>
        /// <param name="pars"></param>
        /// <returns></returns>
        private static string GetParams(SugarParameter[] pars)
        {
            return pars.Aggregate("", (current, p) => current + $"{p.ParameterName}:{p.Value}, ");
        }

        

    }
}
